#include "tcp_socket.hpp"
#include <sstream>

int main(int argc,char* argv[])
{
  if(argc != 2){
    std::cout<<"./http_server port\n";
    return -1;
  }
  int srv_port = std::stoi(argv[1]);
  std::string srv_ip = "0.0.0.0";

  TcpSocket lst_sock;
  CHECK_RET(lst_sock.Socket());
  CHECK_RET(lst_sock.Bind(srv_ip, srv_port));
  CHECK_RET(lst_sock.Listen());
  while(1){
    TcpSocket new_sock;
    bool ret = lst_sock.Accept(&new_sock);
    if(ret == false){
      continue;
    }
    std::string req;
    new_sock.Recv(&req);
    size_t pos = req.find("\r\n\r\n");
    if(pos == std::string::npos){
      //没有找到头部结尾标志，认为头部过大
      //将响应状态码设置为 414 Request-URI Too Large
      return -1;
    }
    std::string header = req.substr(0,pos);//从0位置到pos位置就是头部
    //按理应该是将头部按照\r\n进行分割，逐个取出头部，
    //然后根据头部中的Content-Lengh确定正文长度，然后在获取正文
    //剩下的正文长度就是 req.size() - header.size() -4
    std::string body = req.substr(pos + 4);//从pos+4位置截取到结尾
    std::cout<<"header:["<< header <<"]\n";
    std::cout<<"body:["<< body <<"]\n";

    std::string rsp = "<html><body><h1>zp sb</h1></body></html>";
    std::stringstream ss;//定义一个string流
    ss << "HTTP/1.1 302 Found\r\n";
    ss << "Connection: close\r\n";
    ss << "Content-Type: application/octet-stream\r\n";
    ss << "Content-Length: "<< rsp.size() << "\r\n";
    ss << "Location: https://www.baidu.com\r\n";
    ss << "\r\n";
    ss << rsp;
    std::cout << "response:["<< ss.str() <<"]\n"; //将ss转换为字符串进行打印
    new_sock.Send(ss.str());
    new_sock.Close();
  }
  lst_sock.Close();
  return 0;
}
